package com.congee02.modelshellmvn.controller;

import com.congee02.modelshellmvn.advice.UniformMessage;
import com.congee02.modelshellmvn.entity.account.Account;
import com.congee02.modelshellmvn.exception.AlreadyLoginException;
import com.congee02.modelshellmvn.service.AccountService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.congee02.modelshellmvn.consts.CommonConsts.ACCOUNT_SESSION_ATTRIBUTE_KEY;

@RestController
public class AccountController {

    @Resource
    private HttpServletRequest request;

    @Resource
    private AccountService accountService;

    private final static String SESSION_LOGIN_ATTRIBUTE = ACCOUNT_SESSION_ATTRIBUTE_KEY;

    private HttpSession session() {
        return request.getSession();
    }

    @PostMapping(value = "login")
    public UniformMessage login(
            @RequestBody Account loginAccount
    ) {
        if (loginAccount.getJwt() != null) {
            throw new AlreadyLoginException();
        }
        Account account = accountService.login(loginAccount);
        session().setAttribute(SESSION_LOGIN_ATTRIBUTE, account);
        return UniformMessage.ok("登录成功", account);
    }

    @GetMapping(value = "logout")
    public void logout(
            @RequestBody Account account
    ) {
        if (account == null) {
            return;
        }
        // todo JWT black-list
    }

    @GetMapping("current")
    public Account currentAccount(
            @RequestHeader("Authorization") String token
    ) {
        return accountService.current(
                new Account().setJwt(
                        token
                )
        );
    }

    @PostMapping("register")
    public Account register(@RequestBody Account account) {
        return accountService.register(account);
    }

}
